<?php
// +----------------------------------------------------------------------
// | 权限分配控制器
// +----------------------------------------------------------------------
// | date:2017-05-17
// +----------------------------------------------------------------------
// | Author: lzb
// +-------------------------------------------------
namespace Admin\Controller;

use Common\Controller\AdminBaseController;

/**
 * 后台权限管理
 */
class AgentController extends AdminBaseController
{

    /**
     * 代理商列表
     */
    public function one_agent_user_list()
    {
        $agent_name = trim(I('post.agent_name'));
        if ($agent_name) {
            $map['admin_name'] = ['like', '%' . $agent_name . '%'];
        }
        //分页相关
        $agent = M('agent');
        $map['dengji'] = 1;
        $total = $agent->where($map)->count();

        $pageSize = 5;
        $page = new \Think\Page($total, $pageSize);
        pages($page, $map);
        if ($pageSize < $total) {
            $show = $page->show();
        }

        $data = $agent->where($map)->limit($page->firstRow, $page->listRows)->order('admin_id asc')->select();
        foreach ($data as $key => $value) {
            $data[$key]['last_login_time'] = date("Y-m-d H:i", $value['last_login_time']);
            $shangjiname = D('agent')->where('admin_id=' . $value['shangji'])->find();
            if ($shangjiname['shangji'] == 0) {
                $data[$key]['shangjiname'] = '平台';
            } else {
                $data[$key]['shangjiname'] = $shangjiname['admin_name'];
            }
        }

        $this->assign('num', $total);
        $this->assign('agent_name', $agent_name);
        $this->assign('list', $data);
        $this->assign('show', $show);
        $this->display();
    }


    public function two_agent_user_list()
    {
        $agent_name = trim(I('post.agent_name'));
        if ($agent_name) {
            $map['admin_name'] = ['like', '%' . $agent_name . '%'];
        }
        //分页相关
        $agent = M('agent');
        $map['dengji'] = 2;
        $total = $agent->where($map)->count();

        $pageSize = 5;
        $page = new \Think\Page($total, $pageSize);
        pages($page, $map);
        if ($pageSize < $total) {
            $show = $page->show();
        }

        $data = $agent->where($map)->limit($page->firstRow, $page->listRows)->order('admin_id asc')->select();
        foreach ($data as $key => $value) {
            $data[$key]['last_login_time'] = date("Y-m-d H:i", $value['last_login_time']);
            $data[$key]['dengji'] = "二级";
            $shangjiname = D('agent')->where('admin_id=' . $value['shangji'])->find();
            $data[$key]['shangjiname'] = $shangjiname['admin_name'];
        }

        $this->assign('num', $total);
        $this->assign('agent_name', $agent_name);
        $this->assign('list', $data);
        $this->assign('show', $show);
        $this->display();
    }

    public function three_agent_user_list()
    {
        $agent_name = trim(I('get.agent_name'));
        if ($agent_name) {
            $map['admin_name'] = ['like', '%' . $agent_name . '%'];
        }
        //分页相关
        $agent = M('agent');
        $map['dengji'] = 3;
        $total = $agent->where($map)->count();

        $pageSize = 5;
        $page = new \Think\Page($total, $pageSize);
        pages($page, $map);
        if ($pageSize < $total) {
            $show = $page->show();
        }

        $data = $agent->where($map)->limit($page->firstRow, $page->listRows)->order('admin_id asc')->select();
        foreach ($data as $key => $value) {
            $data[$key]['last_login_time'] = date("Y-m-d H:i", $value['last_login_time']);
            $data[$key]['dengji'] = "三级";
            $shangjiname = D('agent')->where('admin_id=' . $value['shangji'])->find();
            $data[$key]['shangjiname'] = $shangjiname['admin_name'];
        }

        $this->assign('num', $total);
        $this->assign('agent_name', $agent_name);
        $this->assign('list', $data);
        $this->assign('show', $show);//分页
        $this->display();
    }

    /**
     * 平台添加一级代理商
     */
    public function add_admin()
    {
        if (IS_POST) {
            $admin_name = trim(I('post.admin_name'));
            $admin_password = trim(I('post.admin_password'));
            $phone = trim(I('post.phone'));
            $email = trim(I('post.email'));
            $status = I('post.status');
            if (empty($admin_name) || !isNames($admin_name, 6, 20)) {
                $this->error('请输入6-20位的账号');
            }
            if (empty($admin_password) || !isPWD($admin_password, 6, 20)) {
                $this->error('请输入6-20位的密码');
            }
            //检查账号是否已存在
            $admin_info = M('Agent')->field('admin_id')->where(array('admin_name' => $admin_name))->find();
            if (!empty($admin_info)) {
                $this->error('账号已存在');
            }
            $data = array(
                'admin_name' => $admin_name,
                'admin_password' => md5($admin_password),
                'phone' => $phone,
                'email' => $email,
                'status' => $status,
                'register_time' => time(),
                'dengji' => 1,
                'shangji' => 0,
            );

            $result = D('Agent')->addAgent($data);
            if ($result) {
                //保存运营商折扣率数据
                $instance = I('post.instance'); //实例
                $system_disk = I('post.system_disk'); //系统盘
                $storage_disc = I('post.storage_disc'); //存储盘
                $network = I('post.network'); //公网带宽
                foreach ($instance as $index => $item) {
                    $data = [];
                    $data['agent_id'] = $result;
                    $data['is_agent'] = 1;
                    $data['operator_id'] = $index;
                    $data['instance'] = $item;
                    $data['system_disk'] = $system_disk[$index];
                    $data['storage_disc'] = $storage_disc[$index];
                    $data['network'] = $network[$index];
                    $result1 = M('mid_relation')->add($data);
                }
                //新添加的代理商 权限组设置
                $group = array(
                    'uid' => $result,
                    'group_id' => 2,  //组权限统一都设置为代理商组的权限
                );
                D('AuthGroupAccess')->addData($group);
                $this->success('添加成功', U('Admin/Agent/one_agent_user_list'));
            } else {
                $this->error('添加失败', U('Admin/Agent/one_agent_user_list'));
            }
        } else {
            //查询所有的运营商折扣信息：
            $data = M('operator')->getField('id, operator_name, cate');
            $this->assign('list', $data);
            $this->display();
        }
    }

    /**
     * 修改下级代理商
     */
    public function edit_one_agent()
    {
        if (IS_POST) {
            $admin_id = I('post.admin_id');
            $phone = trim(I('post.phone'));
            $email = trim(I('post.email'));
            $status = I('post.status');
            $dengji = I('post.dengji');
            if (empty($admin_id)) {
                $this->error('管理员id异常');
            }
            $data = array(
                'admin_id' => $admin_id,
                'phone' => $phone,
                'email' => $email,
                'status' => $status,
            );
            //平台只对一级代理商的折扣进行修改
            if ($dengji == 1) {
                $instance = I('post.instance'); //实例
                $system_disk = I('post.system_disk'); //系统盘
                $storage_disc = I('post.storage_disc'); //存储盘
                $network = I('post.network'); //公网带宽
                foreach ($instance as $index => $item) {
                    $data = [];
                    $data['id'] = $index;
                    $data['instance'] = $item;
                    $data['system_disk'] = $system_disk[$index];
                    $data['storage_disc'] = $storage_disc[$index];
                    $data['network'] = $network[$index];
                    $result = M('mid_relation')->save($data);

                    // 保存相关的折扣率编辑记录
                    $old_log = M('mid_relation')
                        ->alias('m')
                        ->field('m.*, o.operator_name')
                        ->join('__OPERATOR__ o ON m.operator_id=o.id', 'LEFT')
                        ->where('m.id=' . $index)
                        ->find();
                    $depict = sprintf("详情：运营商【%4s】 的
                    实例：%4f --> %f, 
                    系统盘：%4f --> %4f,
                    存储盘：%4f --> %4f,
                    公网带宽：%4f --> %4f",
                        $old_log['operator_name'],
                        $old_log['instance'], $instance[$index],
                        $old_log['system_disk'], $system_disk[$index],
                        $old_log['storage_disc'], $storage_disc[$index],
                        $old_log['network'], $network[$index]);

                    $log= [];
                    $log['who'] = '代理商';
                    $log['target'] = $old_log['operator_name'];
                    $log['agent_id'] = $old_log['agent_id'];
                    $log['is_agent'] = 0;
                    $log['depict'] = $depict;
                    $log['time'] = date('Y-m-d H:i:s', time());
                    $result = M('rate_update_log')->add($log);
                }
            }
            $data = D('Agent')->editAgent($data);
            if (!$data['state']) {
                $this->error($data['msg']);
            }
            // 操作成功
            $this->success($data['msg'], U('agent/one_agent_user_list'));

        } else {

            $agent_id = I('get.id', 0, 'intval');
            if (empty($agent_id)) {
                $this->error('管理员id异常');
            }
            $where['admin_id'] = $agent_id;
            //平台只对一级代理商有修改权限。二级和三级代理商由其父级代理商进行管理
            $agent_info = M('agent')->where($where)->getField('admin_id,admin_name,dengji,phone,email,status');
            //查询所有的运营商折扣信息：
            $where = array();
            $where['agent_id'] = $agent_id;


            $data = M('mid_relation')
                ->alias('m')
                ->field('m.*, o.operator_name')
                ->join('__OPERATOR__ o ON m.operator_id=o.id', 'LEFT')
                ->order('m.id ASC')
                ->where($where)
                ->select();

            if (empty($agent_info)) {
                $this->error('管理员id异常');
            }
            $level = '平台';
            if ($agent_info[$agent_id]['dengji'] == 1) {
                $level = '一级';
            } elseif ($agent_info[$agent_id]['dengji'] == 2) {
                $level = '二级';
            } elseif ($agent_info[$agent_id]['dengji'] == 3) {
                $level = '三级';
            }
            $agent_info[$agent_id]['level'] = $level;
            $this->assign('list', $data);
            $this->assign('agent_info', $agent_info[$agent_id]);
            $this->display();
        }
    }

    /**
     * 修改代理商密码
     */
    public function change_pwd_by_agent_id()
    {
        if (IS_POST) {
            $admin_id = I('post.admin_id');
            $admin_password = trim(I('post.admin_password'));
            $repassword = trim(I('post.repassword'));
            if (empty($admin_password) || !isPWD($admin_password, 6, 20)) {
                $this->error('请输入6-20位的密码');
            }
            if (empty($admin_id)) {
                $this->error('管理员id异常');
            }
            $data = array(
                'admin_id' => $admin_id,
                'admin_password' => $admin_password,
                'repassword' => $repassword,
            );
            $data = D('Agent')->editAgentPwd($data);
            if (!$data['state']) {
                $this->error($data['msg']);
                exit();
            }
            // 操作成功
            $this->success($data['msg'], U('agent/one_agent_user_list'));

        } else {
            $agent_id = I('get.id', 0, 'intval');
            if (empty($agent_id)) {
                $this->error('管理员id异常');
            }
            $where['admin_id'] = $agent_id;
            $agent_info = M('agent')->where($where)->getField('admin_id,admin_name,phone,dengji');
            if (empty($agent_info)) {
                $this->error('管理员id异常');
            }

            $level = '平台';
            if ([$agent_id]['dengji'] == 1) {
                $level = '一级';
            } elseif ($agent_info[$agent_id]['dengji'] == 2) {
                $level = '二级';
            } elseif ($agent_info[$agent_id]['dengji'] == 3) {
                $level = '三级';
            }
            $agent_info[$agent_id]['level'] = $level;
            $this->assign('agent_info', $agent_info[$agent_id]);
            $this->display();
        }
    }

    //查看下级代理商列表：
    public function get_children_agent_list()
    {
        $agent_id = I('get.id', 0, 'intval');
        $agent = M('agent');
        $agent_info = $agent->where('admin_id=' . $agent_id)->find();

        $map['shangji'] = $agent_id;
        $total = $agent->where($map)->count();

        $pageSize = 10;
        $page = new \Think\Page($total, $pageSize);
        pages($page, $map);
        if ($pageSize < $total) {
            $show = $page->show();
        }
        $children_agent_list = $agent->where($map)->limit($page->firstRow, $page->listRows)->order('admin_id asc')->select();

        foreach ($children_agent_list as $key => $value) {
            $level = '平台';
            if ($children_agent_list[$key]['dengji'] == 1) {
                $level = '一级';
            } elseif ($children_agent_list[$key]['dengji'] == 2) {
                $level = '二级';
            } elseif ($children_agent_list[$key]['dengji'] == 3) {
                $level = '三级';
            }
            $children_agent_list[$key]['level'] = $level;
            $children_agent_list[$key]['shangjiname'] = $agent_info['admin_name'];
        }
        $this->assign('title', $agent_info);
        $this->assign('list', $children_agent_list);
        $this->assign('show', $show);//分页
        $this->display();

    }

    //修改代理商信息
    public function editAgentPwd($agentInfo)
    {
        $rules = array(
            //密码
            array('admin_password', 'require', '密码不能为空!'), // 自定义函数验证密码格式
            //确认密码
            array('repassword', 'admin_password', '确认密码不正确', 0, 'confirm'), // 验证确认密码是否和密码一致
        );
        $Agent = M("Agent"); // 实例化User对象
        if (!$Agent->validate($rules)->create()) {
            // 验证不通过返回错误
            $data['state'] = false;
            $data['msg'] = $Agent->getError();
            return $data;
        } else {
            // 验证通过
            $where['admin_id'] = $agentInfo['admin_id'];
            unset($agentInfo['admin_id']);
            unset($agentInfo['repassword']);
            M('agent')->where($where)->save($agentInfo);
            $data['state'] = true;
            $data['msg'] = "代理商密码更新成功";
            return $data;
        }

    }

    //查看下级会员列表：
    public function get_children_user_list()
    {
        $agent_id = I('get.id', 0, 'intval');
        $agent = M('agent');
        $agent_info = $agent->where('admin_id=' . $agent_id)->find();

        $user = M('user');
        $map['agent_id'] = $agent_id;
        $total = $user->where($map)->count();

        $pageSize = 10;
        $page = new \Think\Page($total, $pageSize);
        pages($page, $map);
        if ($pageSize < $total) {
            $show = $page->show();
        }
        $children_user_list = $user->where($map)->limit($page->firstRow, $page->listRows)->order('add_agent_time asc')->select();
        $this->assign('title', $agent_info);
        $this->assign('list', $children_user_list);
        $this->assign('show', $show);//分页
        $this->display();
    }

    //查看某个会员的订单列表：
    public function get_order_list_by_userId()
    {
        $user_id = I('get.id', 0, 'intval');
        $agent_id = I('get.agent_id', 0, 'intval');
        $agent_info = M('agent')->where('admin_id=' . $agent_id)->find();
        $user = M('user');
        $user_info = $user->where('id=' . $user_id)->find();

        $order = M('order');
        $map['uid'] = $user_id;
        $total = $order->where($map)->count();

        $pageSize = 10;
        $page = new \Think\Page($total, $pageSize);
        pages($page, $map);
        if ($pageSize < $total) {
            $show = $page->show();
        }
        $order_list = $order->where($map)->limit($page->firstRow, $page->listRows)->order('ordertime desc')->select();
        foreach ($order_list as $k => $v) {
            $order_list[$k]['ordertime'] = date('Y-m-d H:i:s', $v['ordertime']);
            if ($order_list[$k]['state'] == 1) {
                $order_list[$k]['state'] = '已付款';
            } else {
                $order_list[$k]['state'] = '待付款';
            }
        }
        $this->assign('user_info', $user_info);
        $this->assign('agent_info', $agent_info);
        $this->assign('list', $order_list);
        $this->assign('show', $show);//分页
        $this->display();
    }

    //获取折扣率修改记录（指定代理商id的 ）
    public function get_rate_update_log()
    {
        $agent_id = I('get.id', 0, 'intval');
        $agent_info = M('agent')->where('admin_id=' . $agent_id)->find();

        $keyword = trim(I('keyword'));
        //搜索关键词
        if(!empty($keyword)){
            //设置查询条件,模糊查询
            $map['target'] = array('like',"%$keyword%");
        }

        $rate_update_log = M('rate_update_log');
        $map['agent_id'] = $agent_id;
        $map['is_agent'] = 1;
        $total = $rate_update_log->where($map)->count();

        $pageSize = 10;
        $page = new \Think\Page($total, $pageSize);
        pages($page, $map);
        if ($pageSize < $total) {
            $show = $page->show();
        }
        $log_list = $rate_update_log->where($map)->limit($page->firstRow, $page->listRows)->order('time desc')->select();

        $this->assign('keyword', $keyword);
        $this->assign('agent_info', $agent_info);
        $this->assign('list', $log_list);
        $this->assign('show', $show);//分页
        $this->display();
    }


}
